#include "mainwindow.h"
#include "constants.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QSplitter>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_networkManager(new QNetworkAccessManager(this))
{
    initUI();
}

MainWindow::~MainWindow()
{

}

void MainWindow::initUI()
{
    QWidget *centralWidget = new QWidget(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);

    // URL输入行
    QHBoxLayout *urlLayout = new QHBoxLayout();
    m_typeCombobox = new QComboBox();
    m_typeCombobox->setMinimumWidth(100);
    m_typeCombobox->addItem("Get", RequestType::Get);
    m_typeCombobox->addItem("Post", RequestType::Post);
    m_typeCombobox->addItem("Put", RequestType::Put);
    m_typeCombobox->addItem("Delete", RequestType::Delete);
    m_urlEdit = new QLineEdit(XLL::DefaultURL);
    m_sendButton = new QPushButton("Send");
    urlLayout->addWidget(m_typeCombobox);
    urlLayout->addWidget(m_urlEdit);
    urlLayout->addWidget(m_sendButton);

    // 请求界面
    m_headersEdit = new QPlainTextEdit();
    m_headersEdit->setPlaceholderText("Enter headers (Format: Key: Value)");
    m_headersEdit->setPlainText(XLL::getHeadersString());

    m_bodyEdit = new QPlainTextEdit();
    m_bodyEdit->setPlaceholderText("Enter body");

    QTabWidget *requestTabWidget = new QTabWidget(centralWidget);
    requestTabWidget->addTab(m_headersEdit, "Request Headers");
    requestTabWidget->addTab(m_bodyEdit, "Request Body");

    // 响应显示
    QWidget *responseWidget = new QWidget(centralWidget);
    QVBoxLayout *responseLayout = new QVBoxLayout(responseWidget);
    m_responseEdit = new QTextEdit();
    m_responseEdit->setReadOnly(true);
    responseLayout->addWidget(new QLabel("Response:"));
    responseLayout->addWidget(m_responseEdit);

    QSplitter *bodySplitter = new QSplitter();
    bodySplitter->addWidget(requestTabWidget);
    bodySplitter->addWidget(responseWidget);

    mainLayout->addLayout(urlLayout);
    mainLayout->addWidget(bodySplitter);

    m_urlEdit->setFocus();
    setCentralWidget(centralWidget);
    resize(800, 600);

    // 连接信号槽
    connect(m_sendButton, &QPushButton::clicked, this, &MainWindow::onSendRequest);
}

void MainWindow::handleResponse(QNetworkReply *reply)
{
    qInfo() << "Response received" << reply->error();
    QString responseText;

    // 处理错误
    if (reply->error() != QNetworkReply::NoError) {
        responseText = QString("Error: %1\n%2").arg(reply->errorString()).arg(reply->readAll());
    } else {
        // 构建响应信息
        responseText += QString("Status: %1\n").arg(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt());

        // 响应头
        responseText += "\nHeaders:\n";
        foreach (const QNetworkReply::RawHeaderPair &pair, reply->rawHeaderPairs()) {
            responseText += QString("%1: %2\n").arg(QString(pair.first)).arg(QString(pair.second));
        }

        // 响应体
        responseText += "\nBody:\n";
        responseText += QString::fromUtf8(reply->readAll());
    }

    m_responseEdit->setText(responseText);

    reply->close();
    reply->deleteLater();
    reply = nullptr;

    m_sendButton->setEnabled(true);
}

void MainWindow::onSendRequest()
{
    m_responseEdit->clear();
    QString url = m_urlEdit->text().trimmed();
    if (url.isEmpty())
        return;

    m_sendButton->setEnabled(false);

    QNetworkRequest request;
    request.setUrl(QUrl(url));

    // 初始化请求头
    initRequestHeader(request);

    // 获取body数据
    QString bodyText = m_bodyEdit->toPlainText();
    QByteArray data = bodyText.toLatin1();

    qInfo()<<"Request URL: " << url;
    qInfo()<<"--------Request Headers-------";
    for (const QByteArray &header : request.rawHeaderList()) {
        qInfo() << header << ":" << request.rawHeader(header);
    }
    qInfo()<<"------------------------------";
    qInfo()<<"Request Body: " << bodyText;

    // 发送请求
    QNetworkReply *reply;
    RequestType type = m_typeCombobox->currentData().value<RequestType>();
    switch (type) {
    case Get:
        reply = m_networkManager->get(request);
        break;
    case Post:
        reply = m_networkManager->post(request, data);
        break;
    case Put:
        reply = m_networkManager->put(request, data);
        break;
    case Delete:
        reply = m_networkManager->deleteResource(request);
        break;
    default:
        break;
    }

    connect(reply, &QNetworkReply::finished, this, [this, reply]() {
        handleResponse(reply);
    });
}

void MainWindow::initRequestHeader(QNetworkRequest &request)
{
    QString headersText = m_headersEdit->toPlainText();
    QStringList headers = headersText.split('\n', Qt::SkipEmptyParts);
    for (const QString &header : headers) {
        int colonPos = header.indexOf(':');
        if (colonPos > 0) {
            QString key = header.left(colonPos).trimmed();
            QString value = header.mid(colonPos + 1).trimmed();
            request.setRawHeader(key.toUtf8(), value.toUtf8());
        }
    }
}
